package com.loyal.camerax.view

import android.content.Context
import android.graphics.Color
import android.graphics.Point
import android.util.AttributeSet
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.widget.FrameLayout
import androidx.appcompat.widget.AppCompatImageView
import androidx.camera.core.CameraControl
import androidx.camera.view.CameraController
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import com.loyal.camerax.R
import java.util.concurrent.ExecutionException

/**
 * 对焦动图显示
 */
class FocusImageView : AppCompatImageView {
    private val mAnimation: Animation

    constructor(context: Context) : super(context) {
        mAnimation = AnimationUtils.loadAnimation(context, R.anim.focus)
        visibility = INVISIBLE
        setImageResource(R.drawable.ic_focus)
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        mAnimation = AnimationUtils.loadAnimation(context, R.anim.focus)
        visibility = INVISIBLE
        setImageResource(R.drawable.ic_focus)
    }

    /**
     * 显示对焦图案
     */
    fun startFocus(point: Point) {
        removeCallbacks(invisibilityRunnable)
        //根据触摸的坐标设置聚焦图案的位置
        val params = layoutParams as ViewGroup.LayoutParams
        if (params is FrameLayout.LayoutParams) {
            params.topMargin = point.y - measuredHeight / 2
            params.leftMargin = point.x - measuredWidth / 2
            layoutParams = params
        } else if (params is ConstraintLayout.LayoutParams) {
            params.topMargin = point.y - measuredHeight / 2
            params.leftMargin = point.x - measuredWidth / 2
            layoutParams = params
        }
        //设置控件可见，并开始动画
        visibility = VISIBLE
        setColorFilter(Color.WHITE)
        startAnimation(mAnimation)
    }

    /**
     * 显示对焦图案
     */
    fun focusStateChanged(state: Int) {
        when (state) {
            CameraController.TAP_TO_FOCUS_NOT_STARTED -> {
                visibility = INVISIBLE
                removeCallbacks(invisibilityRunnable)
            }

            CameraController.TAP_TO_FOCUS_STARTED -> {
                val point = tag as? Point?
                point?.let {
                    startFocus(it)
                }
            }

            CameraController.TAP_TO_FOCUS_FOCUSED -> focus(true)

            CameraController.TAP_TO_FOCUS_NOT_FOCUSED, CameraController.TAP_TO_FOCUS_FAILED ->
                focus(false)
        }
    }

    private val invisibilityRunnable = Runnable {
        visibility = INVISIBLE
    }

    fun focus(success: Boolean) {
        removeCallbacks(invisibilityRunnable)
        visibility = VISIBLE
        val res = if (success) R.color.focusSuccess else R.color.focusFail
        val color = ContextCompat.getColor(context, res)
        setColorFilter(color)
        //移除在startFocus中设置的callback，1秒后隐藏该控件
        postDelayed(invisibilityRunnable, 800L)
    }

    fun focusError(e: Exception?) {
        if (e is ExecutionException || e is InterruptedException || e is CameraControl.OperationCanceledException) {
            //第一次聚焦未完成后，开始第二次聚焦
            removeCallbacks(invisibilityRunnable)
            visibility = INVISIBLE
        }
    }

    companion object {
        private const val TAG = "FocusImageView"

    }
}
